package com.self.cloudmall.cart.interceptor;

import com.self.cloudmall.cart.bo.UserCartBo;
import com.self.cloudmall.common.constant.CartConstant;
import com.self.cloudmall.common.constant.PmsConstant;
import com.self.cloudmall.common.constant.SsoConstant;
import com.self.cloudmall.common.dto.LoginUserDto;
import com.self.cloudmall.common.utils.CookieUtil;
import com.self.cloudmall.common.utils.ThreadLocalUtil;
import com.self.cloudmall.common.utils.UUIDUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * @version v1.0
 * @ClassName: UserCartInterceptor
 * @Description:
 * @Author: M10003729
 */
@Slf4j
@Component
public class UserCartInterceptor implements HandlerInterceptor {


    /**
     * @Title: 前置处理：
     *      验证用户是否登录，如果没有登录，使用临时购物车，生成user-key保存到cookie里，有效期一个月
     *      ，带上user-key
     *      如果登录了，带上user-key
     * @Description:
     * @Param [request, response, handler]
     * @Return boolean
     * @Author M10003729
     * @Throws
     * @Date 2020/12/11 11:29
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        UserCartBo userCartBo = new UserCartBo();
        HttpSession session = request.getSession();
        LoginUserDto attribute = (LoginUserDto)session.getAttribute(SsoConstant.LOGIN_USER);
        if (attribute != null){
            userCartBo.setUserId(attribute.getId());
        }
        String cookieValue = CookieUtil.getCookieValue(request, CartConstant.TEMP_USER_KEY_NAME);
        //是否有cookie值，如果有表示是临时用户，否则生成user-key,表示身份
        if (StringUtils.isNotEmpty(cookieValue)){
            userCartBo.setUserKey(cookieValue);
            userCartBo.setTempUser(true);
        }else{
            userCartBo.setUserKey(UUIDUtil.generateUUID());
        }
        ThreadLocalUtil.set(userCartBo);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserCartBo cartBo = ThreadLocalUtil.get();
        if (!cartBo.isTempUser()){
            //如果不是临时用户，则延长cookie时间
            CookieUtil.addCookie(response, CartConstant.TEMP_USER_KEY_NAME,cartBo.getUserKey(),CartConstant.TEMP_USER_KEY_EXPIRE,SsoConstant.ROOT_DOMAIN);
        }
        ThreadLocalUtil.remove();
    }
}
